package logic

import (
	"context"
	"fmt"
	"good_srv/cache"
	"good_srv/good"
	"good_srv/internal/svc"
	"good_srv/models"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type CartAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCartAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CartAddLogic {
	return &CartAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 购物车添加
func (l *CartAddLogic) CartAdd(in *good.CartAddRequest) (*good.CartAddResponse, error) {
	// todo: add your logic here and delete this line
	//判断商品是否存在
	var err error
	goods := models.Good{
		Model: gorm.Model{
			ID: uint(in.GoodsId),
		},
	}
	if err = goods.Detail(); err != nil {
		logx.Error("商品详情成功")
		return nil, fmt.Errorf("商品详情成功")
	}
	//判断库存是否充足
	if in.Num > int64(goods.Stock) {
		logx.Error("库存不充足")
		return nil, fmt.Errorf("库存不充足")
	}
	//如果商品存在就更新 不存在就添加
	if cache.CartExist(int(in.UserId), int(in.GoodsId)) {
		cache.CartUpdate(int(in.UserId), int(in.GoodsId), int(in.Num))
	} else {
		goodMap := map[string]interface{}{
			"title":   goods.Title,
			"price":   goods.Price,
			"image":   goods.Image,
			"stock":   goods.Stock,
			"num":     in.Num,
			"userId":  in.UserId,
			"goodsId": in.GoodsId,
		}
		cache.GoodAdd(int(in.UserId), int(in.GoodsId), goodMap)
	}
	return &good.CartAddResponse{}, nil
}
